package xcmg.device.service.logistics;

import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xcmg.device.dao.entity.company.CompanyDealerDO;
import xcmg.device.dao.entity.company.CompanyInfoDO;
import xcmg.device.dao.entity.company.CompanySupplierDO;
import xcmg.device.dao.entity.delivery.DeliveryReceiptLogisticsDO;
import xcmg.device.dao.entity.logistics.SendBillDO;
import xcmg.device.dao.entity.logistics.SendBillDetailDO;
import xcmg.device.dao.entity.marketing.MarketingActivityDO;
import xcmg.device.dao.entity.purchase.PurchaseInboundDO;
import xcmg.device.dao.entity.purchase.PurchaseInboundDetailDO;
import xcmg.device.dao.entity.purchase.PurchaseRequestDO;
import xcmg.device.dao.entity.purchase.PurchaseRequestDetailDO;
import xcmg.device.dao.entity.sale.SaleIntentionDO;
import xcmg.device.dao.entity.sale.SaleIntentionDetailDO;
import xcmg.device.dao.entity.warehouse.WarehouseAreaDO;
import xcmg.device.dao.entity.warehouse.WarehouseAreaLocationDO;
import xcmg.device.dao.entity.warehouse.WarehouseDO;
import xcmg.device.dao.mapper.*;
import xcmg.device.dao.mapper.delivery.DeliveryReceiptLogisticsMapper;
import xcmg.device.dao.mapper.logistics.SendBillDetailMapper;
import xcmg.device.dao.mapper.logistics.SendBillMapper;
import xcmg.device.dao.mapper.taskRecord.TaskRecordMapper;
import xcmg.device.dao.mapper.warehouse.WarehouseAreaDOMapper;
import xcmg.device.dao.mapper.warehouse.WarehouseAreaLocationDOMapper;
import xcmg.device.dao.mapper.warehouse.WarehouseDOMapper;
import xcmg.device.infra.*;
import xcmg.device.infra.enums.BillDesc;
import xcmg.device.infra.enums.CompanyTypeEnum;
import xcmg.device.infra.enums.DeliveryStatus;
import xcmg.device.infra.enums.SaleStatus;
import xcmg.device.service.GenDocumentService;
import xcmg.device.service.delivery.DeliveryNoteService;
import xcmg.device.service.purchase.PurchaseInboundService;
import xcmg.device.service.purchase.PurchaseRequestService;
import xcmg.device.service.sale.SaleIntentionService;
import xcmg.device.service.vo.basic.MaterialsSearchVO;
import xcmg.device.service.vo.basic.MaterialsVO;
import xcmg.device.service.vo.delivery.DeliveryNoteAddVO;
import xcmg.device.service.vo.delivery.DeliveryNoteDetailVO;
import xcmg.device.service.vo.delivery.DeliveryNoteVO;
import xcmg.device.service.vo.delivery.DeliveryReceiptLogisticsVO;
import xcmg.device.service.vo.logistics.SendBillAddVO;
import xcmg.device.service.vo.logistics.SendBillDetailVO;
import xcmg.device.service.vo.logistics.SendBillVO;
import xcmg.device.service.vo.marketing.MarketingActivityVO;
import xcmg.device.service.vo.marketing.MarketingMaterialsVO;
import xcmg.device.service.vo.purchase.PurchaseRequestVO;
import xcmg.device.service.vo.sale.SaleAddVO;
import xcmg.device.service.vo.sale.SaleIntentionDetailVO;
import xcmg.device.service.vo.sale.SaleIntentionVO;
import xcmg.device.service.warehouse.WarehouseDeliveryService;
import xcmg.device.service.warehouse.WarehouseInboundService;
import xcmg.device.util.CompanyUtil;
import yb.ecp.fast.dto.UserCacheDTO;
import yb.ecp.fast.feign.AuthClient;
import yb.ecp.fast.feign.FastGenClient;
import yb.ecp.fast.infra.infra.ActionResult;
import yb.ecp.fast.infra.infra.PageCommonVO;
import yb.ecp.fast.infra.infra.SearchCommonVO;
import yb.ecp.fast.infra.util.ListUtil;
import yb.ecp.fast.infra.util.PageHelperPlus;
import yb.ecp.fast.infra.util.StringUtil;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SendBillService {

    @Autowired
    private SendBillMapper sendBillMapper;

    @Autowired
    private SendBillDetailMapper sendBillDetailMapper;

    @Autowired
    private FastGenClient fastGenClient;

    @Autowired
    private GenDocumentService genDocumentService;

    @Autowired
    private HttpServletResponse response;

    @Autowired
    private PurchaseRequestMapper purchaseRequestMapper;

    @Autowired
    private PurchaseRequestDetailMapper purchaseRequestDetailMapper;

    @Autowired
    private WarehouseInboundService warehouseInboundService;

    @Autowired
    private SaleIntentionMapper saleIntentionMapper;

    @Autowired
    private SaleIntentionService saleIntentionService;

    @Autowired
    private WarehouseAreaDOMapper warehouseAreaDOMapper;
    
    @Autowired
    private WarehouseAreaLocationDOMapper warehouseAreaLocationDOMapper;
    
    @Autowired
    private WarehouseDOMapper warehouseDOMapper;

    @Autowired
    private AuthClient authClient;

    @Autowired
    private PurchaseInboundMapper purchaseInboundMapper;

    @Autowired
    private PurchaseInboundDetailMapper purchaseInboundDetailMapper;


    @Autowired
    private PurchaseRequestService purchaseRequestService;

    @Autowired
    private SaleIntentionDetailMapper saleIntentionDetailMapper;

    @Autowired
    private DeliveryNoteService deliveryNoteService;

    @Autowired
    private CompanyDealerMapper companyDealerMapper;

    @Autowired
    private CompanyInfoMapper companyInfoMapper;

    @Autowired
    private PriMaterialsMapper priMaterialsMapper;

    @Autowired
    private MarketingActivityMapper marketingActivityMapper;

    @Autowired
    private MarketingMaterialsMapper marketingMaterialsMapper;
    
    @Autowired
    private CompanyUtil companyUtil;
    
    @Autowired
    private CompanySupplierMapper companySupplierMapper;

    @Autowired
    private WarehouseDeliveryService warehouseDeliveryService;

    @Autowired
    private DeliveryReceiptLogisticsMapper deliveryReceiptLogisticsMapper;


    @Transactional(rollbackFor = Exception.class)
    public ErrorCode add(SendBillAddVO sendBillAddVO, boolean genFlag) throws Exception {
        if (sendBillAddVO.getHeaderInfo() == null || ListUtil.isNullOrEmpty(sendBillAddVO.getMaterialsList())) {
            return ErrorCode.IllegalArument;
        }

        SendBillVO sendBillVO = sendBillAddVO.getHeaderInfo();
        ActionResult<String> textResult = fastGenClient.textGuid();
        if (textResult.getCode() != ErrorCode.Success.getCode()) {
            return ErrorCode.IllegalArument;
        }

        //判断来源采购单是否允许生成送货单
        Set<String> sourceIds = new HashSet<>();
        Set<String> sourceDeliverys = new HashSet<>();
        for(SendBillDetailVO detailVO : sendBillAddVO.getMaterialsList()){
            sourceIds.add(detailVO.getSourceId());
            sourceDeliverys.add(detailVO.getSourceDelivery());
        }
        if(sourceDeliverys.size() > 1){
            throw new Exception("所选采购单的送达方必须相同");
        }
        for(String sourceId : sourceIds){
            int num = purchaseRequestDetailMapper.findInformNum(sourceId);
            if(num > 0){
                throw new Exception("采购单已经创建采购入库单，无法创建送货单");
            }
        }

        SendBillDO sendBillDO = new SendBillDO();
        BeanUtils.copyProperties(sendBillVO, sendBillDO);
        sendBillDO.setId(textResult.getValue());
        sendBillDO.setSendOrder(genDocumentService.getDocumentNo(BillDesc.SendBill));
        sendBillDO.setCreateDate(new Date());
        if(sendBillDO.getApplyOrgId().equals(sendBillDO.getDeliveryOrgId())){
            //申请方与送达方一致，是普通送货单
            sendBillDO.setSendType(0);
        }else{
            //申请方与送达方不一致，是直投送货单
            sendBillDO.setSendType(1);
        }
        boolean success;

        List<SendBillDetailDO> detailDOList = convertDetailDOList(sendBillAddVO, sendBillDO);

        //提交更新状态
        if (genFlag){
            sendBillDO.setIsSubmit(1);//提交
        }
        success = sendBillMapper.insert(sendBillDO)>0;
        if(!success){
            throw new Exception("操作失败");
        }

        //提交时，生成入库单
        if (genFlag){
            //送货单号
            sendBillVO.setSendOrder(sendBillDO.getSendOrder());
            sendBillVO.setSendType(sendBillDO.getSendType());//送货单类型
            //添加非生效入库单（供应商打印）
            warehouseInboundService.saveBySendBill(sendBillAddVO, sendBillDO.getCreateId(),
                    sendBillVO.getDeliveryOrgId(), sendBillVO.getApplyOrgId(), 1);

            //添加出库库
            warehouseDeliveryService.saveBySendBillOut(sendBillAddVO, sendBillDO.getCreateId(), sendBillVO.getSoldOrgId());

        }

        //更新采购申请单中发货单已通知数量
        updateRemoveInformQty(detailDOList, sendBillDetailMapper.findSourceId(sendBillDO.getId()), 0);
        return ErrorCode.Success;
    }

    private List<SendBillDetailDO> convertDetailDOList(SendBillAddVO sendBillAddVO, SendBillDO sendBillDO)
            throws Exception {
        boolean success;
        List<SendBillDetailDO> detailDOList = new ArrayList<>();
        for (SendBillDetailVO detailVO : sendBillAddVO.getMaterialsList()) {
            SendBillDetailDO detailDO = new SendBillDetailDO();
            BeanUtils.copyProperties(detailVO, detailDO);
            detailDO.setId(fastGenClient.textGuid().getValue());
            detailDO.setMainId(sendBillDO.getId());
            detailDO.setCustomMaterialsNo(priMaterialsMapper.findCustomMaterialsNo(detailDO.getMaterialsNo(), sendBillDO.getSoldOrgId()));
            success = sendBillDetailMapper.insert(detailDO) > 0;
            if (!success) {
                throw new Exception("操作失败");
            }
            detailDOList.add(detailDO);
        }
        return detailDOList;
    }

    @Transactional(rollbackFor = Exception.class)
    public ErrorCode update(SendBillAddVO sendBillAddVO, boolean genFlag) throws Exception{
        if(sendBillAddVO.getHeaderInfo() == null || ListUtil.isNullOrEmpty(sendBillAddVO.getMaterialsList())){
            return ErrorCode.IllegalArument;
        }
        SendBillVO sendBillVO = sendBillAddVO.getHeaderInfo();
        if(sendBillVO.getIsDelivery() == 1){
            throw new Exception("该送货单已发货，无法修改");
        }
        SendBillDO sendBillDO = new SendBillDO();
        BeanUtils.copyProperties(sendBillVO, sendBillDO);

        //更新采购申请单中发货单已通知数量
        updateRemoveInformQty(sendBillDetailMapper.list(sendBillDO.getId()), sendBillDetailMapper.findSourceId(sendBillDO.getId()), 1);

        boolean success = sendBillDetailMapper.deleteByMainId(sendBillDO.getId()) > 0;
        if(!success){
            throw new Exception("操作失败");
        }

        List<SendBillDetailDO> detailDOList = new ArrayList<>();
        for(SendBillDetailVO detailVO : sendBillAddVO.getMaterialsList()){
            SendBillDetailDO detailDO = new SendBillDetailDO();
            BeanUtils.copyProperties(detailVO, detailDO);
            detailDO.setMainId(sendBillDO.getId());
            success = sendBillDetailMapper.insert(detailDO)>0;
            if(!success){
                throw new Exception("操作失败");
            }
            detailDOList.add(detailDO);
        }

        if (genFlag) {
            sendBillDO.setIsSubmit(1);//提交
        }

        success = sendBillMapper.update(sendBillDO) > 0;
        if(!success){
            throw new Exception("操作失败");
        }

        //提交时，生成入库单
        if (genFlag){
            //添加非生效入库单（供应商打印）
            warehouseInboundService.saveBySendBill(sendBillAddVO, sendBillDO.getCreateId(),
                    sendBillVO.getDeliveryOrgId(), sendBillVO.getApplyOrgId(), 1);
            //添加出库事务单
            warehouseDeliveryService.saveBySendBillOut(sendBillAddVO, sendBillDO.getCreateId(), sendBillVO.getSoldOrgId());

        }

        //更新采购申请单中发货单已通知数量
        updateRemoveInformQty(detailDOList, sendBillDetailMapper.findSourceId(sendBillDO.getId()), 0);
        
        return ErrorCode.Success;
    }

    private void updateRemoveInformQty(List<SendBillDetailDO> list, List<String> sourceIds, int type)throws Exception{
        boolean success;
        for(SendBillDetailDO detailDO : list){
            //更新采购申请单中发货单已通知数量
            PurchaseRequestDetailDO requestDetailDO = purchaseRequestDetailMapper.findByBillIdAndMaterialNo(detailDO.getSourceId(), detailDO.getMaterialsNo(), detailDO.getSourceRowNo());
            if(requestDetailDO == null){
                throw new Exception("未找到采购单详情记录");
            }
            BigDecimal totalQty = BigDecimal.ZERO;
            if(type == 0){
                totalQty = requestDetailDO.getInformQty().add(detailDO.getQty());
                if(totalQty.compareTo(requestDetailDO.getQty()) > 0){
                    throw new Exception("本次送货数量不能大于剩余送货数量");
                }
            }else if(type == 1){
                totalQty = requestDetailDO.getInformQty().subtract(detailDO.getQty());
            }
            success = purchaseRequestDetailMapper.updateInformQty(detailDO.getSourceId(), detailDO.getMaterialsNo(), detailDO.getSourceRowNo(), totalQty)>0;
            if(!success){
                throw new Exception("更新采购单已通知数量失败");
            }
        }

        for(String sourceId : sourceIds){
            Integer state = purchaseRequestDetailMapper.findSendStatus(sourceId);
            state = state==null?0:state;
            success = purchaseRequestMapper.updateSendStatus(sourceId, state)>0;
            if(!success){
                throw new Exception("更新采购单已通知状态失败");
            }
        }
    }

    public PageCommonVO list(SearchCommonVO<SendBillVO> condition, String orgId) {
        PageCommonVO<SendBillVO> pageCommonVO = new PageCommonVO();
        PageHelperPlus.orderBy("create_date desc");
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        condition.getFilters().setBillNosList(xcmg.device.infra.StringUtil.splitList(condition.getFilters().getBillNos()));
        List<SendBillDO> doList = sendBillMapper.list(condition.getFilters());
        List<SendBillVO> voList = new ArrayList<>();
        for (SendBillDO entity : doList) {
            SendBillVO model = new SendBillVO();
            BeanUtils.copyProperties(entity, model);
            String companyName = getSupplierName(model.getApplyOrgId(), model.getDeliveryOrgId(), model.getSoldOrgId());
            if (StringUtils.isNotEmpty(companyName) && orgId.equals(model.getDeliveryOrgId())) {
                model.setSoldOrgName(companyName);
            }
            List<String> purchaseNos = sendBillDetailMapper.getPurchaseNos(entity.getId());
            if(CollectionUtils.isNotEmpty(purchaseNos)) {
                StringBuffer buffer = new StringBuffer();
                for (String purchaseNo : purchaseNos) {
                    buffer.append(purchaseNo).append(',');
                }
                String purchaseNoStr = buffer.substring(0, buffer.length() - 1);
                model.setPurchaseNo(purchaseNoStr);
            }
            voList.add(model);
        }
        pageCommonVO.setPageInfo(new PageInfo(doList));
        pageCommonVO.setPageInfoList(voList);
        return pageCommonVO;
    }
    
    private String getSupplierName(String applyOrgId, String deliveryOrgId, String soldOrgId) {
        if (companyUtil.ynOrgId().equals(applyOrgId) && !companyUtil.ynOrgId().equals(deliveryOrgId)) {
            CompanySupplierDO companySupplierDO = companySupplierMapper.itemBySupplierOrgId(companyUtil.ynOrgId(), soldOrgId);
            if (companySupplierDO != null) {
                return companySupplierDO.getSupplierCode();
            }
        }
        return null;
    }

    //物流列表
    public PageCommonVO list4Logistics(SearchCommonVO<SendBillVO> condition) {
        PageCommonVO<SendBillVO> pageCommonVO = new PageCommonVO();
        PageHelperPlus.orderBy("create_date desc");
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        List<SendBillDO> doList = sendBillMapper.list(condition.getFilters());
        List<SendBillVO> voList = new ArrayList<>();
        for (SendBillDO entity : doList) {
            SendBillVO billVO = new SendBillVO();
            BeanUtils.copyProperties(entity, billVO);
            int recordCount = deliveryReceiptLogisticsMapper.countByDate(entity.getSendOrder(), DateFormatUtils.format(new Date(), "yyyyMMdd"));
            billVO.setRecordFlag(recordCount > 0 ? 1 : 0);
            voList.add(billVO);
        }
        pageCommonVO.setPageInfo(new PageInfo(doList));
        pageCommonVO.setPageInfoList(voList);
        return pageCommonVO;
    }

    @Transactional(rollbackFor = Exception.class)
    public ErrorCode delete(List<String> ids) throws Exception{
        int num = sendBillMapper.findForDeleteByIds(ids);
        if(num > 0){
            throw new Exception("已经发货的送货单不能删除");
        }
        //更新采购申请单中发货单已通知数量
        for(String id : ids){
            updateRemoveInformQty(sendBillDetailMapper.list(id), sendBillDetailMapper.findSourceId(id), 1);
        }
        return sendBillMapper.remove(ids)>0?ErrorCode.Success:ErrorCode.Failure;
    }

    @Transactional(rollbackFor = Exception.class)
    public ErrorCode updateIsDelivery(String id, String orgId, String userId)throws Exception{
        SendBillDO sendBillDO = sendBillMapper.selectByPrimaryKey(id);
        if(!sendBillDO.getSoldOrgId().equals(orgId)){
            throw new Exception("只有供应商才可以发货");
        }

        ErrorCode resultCode = sendBillMapper.updateIsDelivery(id, 1)>0?ErrorCode.Success:ErrorCode.Failure;

        // 发货不进行入库单生成逻辑
//        if(ErrorCode.Success.getCode() == resultCode.getCode()) {
//        	SendBillAddVO sendBillAddVO = item(id, orgId);
//            //添加非生效入库单（供应商打印）
//            warehouseInboundService.saveBySendBill(sendBillAddVO, userId, sendBillAddVO.getHeaderInfo().getDeliveryOrgId(), sendBillAddVO.getHeaderInfo().getApplyOrgId(), 1);
//        }

        return resultCode;
    }

    @Transactional(rollbackFor = Exception.class)
    public synchronized ErrorCode sign(SendBillAddVO sendBillAddVO, String userName, String userId, String orgId)throws Exception{
        SendBillVO sendBillVO = sendBillAddVO.getHeaderInfo();
        SendBillDO sendBillDO = sendBillMapper.selectByPrimaryKey(sendBillVO.getId());
        if(sendBillDO == null){
            return ErrorCode.IllegalArument;
        }
        Integer signStatus=sendBillDO.getIsSign();
        List<String> dealerOrgIds = companyDealerMapper.findDealerOrgIds(orgId);
        if(dealerOrgIds == null){
            dealerOrgIds = new ArrayList<>();
        }
        if(!sendBillDO.getDeliveryOrgId().equals(orgId) && !dealerOrgIds.contains(sendBillDO.getDeliveryOrgId())){
            throw new Exception("只有送达方才可以签收");
        }
        sendBillDO.setIsSign(sendBillVO.getIsSign());
        sendBillDO.setSignNote(sendBillVO.getSignNote());
        sendBillDO.setSignDate(new Date());
        sendBillDO.setSignUser(userName);
        boolean success = sendBillMapper.update(sendBillDO)>0;
        if(!success){
            throw new Exception("签收失败");
        }

        //签收数量修改
        for(SendBillDetailVO detailVO : sendBillAddVO.getMaterialsList()){
            SendBillDetailDO detailDO = new SendBillDetailDO();
            detailDO.setId(detailVO.getId());
            detailDO.setSignQty(detailVO.getSignQty());//签收数量
            success = sendBillDetailMapper.update(detailDO) > 0 ;
            if(!success){
                throw new Exception("操作失败");
            }
        }

        //拒绝签收
        if (sendBillVO.getIsSign() == 2) {
            return ErrorCode.Success;
        }
        if(signStatus == 3){
            return ErrorCode.Success;
        }

        /**
         SendBillAddVO sendBillAddVO = item(sendBillVO.getId(),orgId);
         Integer count = warehouseInboundService.getInvalidCountByBusinessOrder(sendBillAddVO.getHeaderInfo().getSendOrder());
         if(count > 0) {
         //更新入库单信息
         warehouseInboundService.updateInboundToValid(sendBillAddVO, userId, userName, orgId);
         }else {
         //生成入库单
         success = warehouseInboundService.saveBySendBill(sendBillAddVO, userId, orgId, sendBillDO.getApplyOrgId(), null);
         }
         if(!success){
         throw new Exception("签收失败");
         }

         if(!Integer.valueOf(1).equals(sendBillDO.getSendType())) {
         this.addPurchaseBillBySendBill(sendBillDetailMapper.list(sendBillVO.getId()), sendBillDO.getSendOrder(), sendBillDO.getSendType());
        }
         */

        //同步ERP
//        syncErp(sendBillDO.getId());
        
        if(sendBillDO.getSendType() == 1 && sendBillDO.getIsGenerateOrder() == 0){
            //送货单是直投属性时自动生成销售意向单、发货通知单、采购入库单
            this.addBySendBill(sendBillDetailMapper.list(sendBillVO.getId()), sendBillDO.getSendOrder());
            sendBillMapper.updateIsGenerateOrder(sendBillDO.getId(), 1);
            return ErrorCode.Success;
        }
        /*
         * if(sendBillDO.getSendType() == 0) { //自动生成采购入库单，状态为已入库，自动过账
         * this.addPurchaseBillBySendBill(sendBillDetailMapper.list(sendBillVO.getId()),
         * sendBillDO.getSendOrder()); return ErrorCode.Success; }
         */
        return ErrorCode.Success;
    }
    
    /**
     * 同步ERP
     * @throws Exception
     */
//    private void syncErp(String id) throws Exception {
//        if ("1".equals(syncFlag)) {
//            SendBillDO sendBillDO = sendBillMapper.selectByPrimaryKey(id);
//            if (sendBillDO != null) {
//                CompanyInfoDO companyInfoDO = companyInfoMapper.item(sendBillDO.getSoldOrgId());
//                //云内送货单被代理商签收
//                if ("1".equals(companyInfoDO.getCompanyType())) {
//                    syncNobalYnInfo(id, sendBillDO);
//                } else {
//                    //云内直投订单推送ERP
//                    if (Integer.valueOf(1).equals(sendBillDO.getSendType())) {
//                        syncDirectYnInfo(sendBillDO);
//                    }
//                }
//            }
//        }
//    }

//    private void syncDirectYnInfo(SendBillDO sendBillDO) throws Exception {
//        SendBillInfo sendBillInfo = convertSendBillInfo(sendBillDO);
//        if (sendBillInfo != null) {
//            ActionResult result = erpSyncClient.syncSendOrder(sendBillInfo);
//            if (ErrorCode.Success.getCode() != result.getCode()) {
//                throw new Exception(result.getMessage());
//            }
//        }
//    }

//    private void syncNobalYnInfo(String id, SendBillDO sendBillDO) throws Exception {
//        List<SendBillDetailDO> detailDOs = sendBillDetailMapper.list(id);
//        for (SendBillDetailDO detailDO : detailDOs) {
//            SendBillSignStatusVO sendBillSignStatusVO = new SendBillSignStatusVO();
//            sendBillSignStatusVO.setId(sendBillDO.getId());
//            sendBillSignStatusVO.setSendOrder(sendBillDO.getSendOrder());
//            sendBillSignStatusVO.setItemId(detailDO.getId());
//            sendBillSignStatusVO.setQuantity(detailDO.getSignQty());
//            ActionResult result = erpSyncClient.sign(sendBillSignStatusVO);
//            if (ErrorCode.Success.getCode() != result.getCode()) {
//                throw new Exception(result.getMessage());
//            }
//        }
//    }
//
//    private SendBillInfo convertSendBillInfo(SendBillDO sendBillDO) {
//        CompanySupplierDO companySupplierDO = companySupplierMapper.itemBySupplierOrgId(sendBillDO.getApplyOrgId(), sendBillDO.getSoldOrgId());
//
//        if (companySupplierDO == null) {
//            return null;
//        }
//
//        SendBillHeaderVO sendBillHeaderVO = new SendBillHeaderVO();
//        sendBillHeaderVO.setBillId(sendBillDO.getId());
//        sendBillHeaderVO.setBillNo(sendBillDO.getSendOrder());
//        sendBillHeaderVO.setSupplierCode(companySupplierDO.getSupplierCode());
//        sendBillHeaderVO.setSupplierName(companySupplierDO.getCompanyName());
//        CompanyDealerDO companyDealerDO = companyDealerMapper.itemByPlatOrgId(sendBillDO.getDeliveryOrgId());
//        if (companyDealerDO != null) {
//            sendBillHeaderVO.setReceiptCode(companyDealerDO.getDealerCode());
//            sendBillHeaderVO.setReceiptName(companyDealerDO.getCompanyName());
//        }
//        sendBillHeaderVO.setReceiptor(sendBillDO.getContactUser());
//        sendBillHeaderVO.setReceiptAddress(sendBillDO.getAddress());
//        sendBillHeaderVO.setReceiptTel(sendBillDO.getContactTel());
//        if (sendBillDO.getSendTime() != null) {
//            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//            sendBillHeaderVO.setSendTime(format.format(sendBillDO.getSendTime()));
//        }
//        sendBillHeaderVO.setIsread("0");
//        sendBillHeaderVO.setErpReceiveTime(null);
//        sendBillHeaderVO.setWmsImportTime(new Date());
//        List<SendBillDetailDO> detailDOs = sendBillDetailMapper.list(sendBillDO.getId());
//        List<SendBillItemVO> sendBillItemVOs = new ArrayList<SendBillItemVO>();
//        Set<String> sourceOrders = new HashSet<String>();
//        for (SendBillDetailDO detailDO : detailDOs) {
//            SendBillItemVO itemVO = new SendBillItemVO();
//            itemVO.setBillId(sendBillDO.getId());
//            itemVO.setItemId(detailDO.getId());
//            itemVO.setAgentPurchaseNo(detailDO.getInitialOrder());
//            itemVO.setPurchaseNo(detailDO.getSourceOrder());
//            itemVO.setMaterialsNo(detailDO.getMaterialsNo());
//            itemVO.setMaterialsName(detailDO.getMaterialsDes());
//            itemVO.setUnit(detailDO.getUnit());
//            itemVO.setQuantity(detailDO.getQty());
//            itemVO.setSignedQuantity(detailDO.getSignQty());
//            sourceOrders.add(detailDO.getSourceOrder());
//            sendBillItemVOs.add(itemVO);
//        }
//        PurchaseRequestDO first = null;
//
//        for (String sourceOrder : sourceOrders) {
//            PurchaseRequestDO purchaseRequestDO = purchaseRequestMapper.itemByBillNo(sourceOrder);
//            if (null == first) {
//                first = purchaseRequestDO;
//            }
//            if (StringUtils.isNotEmpty(purchaseRequestDO.getDeptCode())) {
//                sendBillHeaderVO.setDeptCode(purchaseRequestDO.getDeptCode());
//                sendBillHeaderVO.setDeptName(purchaseRequestDO.getDeptName());
//                sendBillHeaderVO.setPurchaseCode(purchaseRequestDO.getPurchaseCode());
//                sendBillHeaderVO.setPurchaseName(purchaseRequestDO.getPurchaseName());
//                if (StringUtils.isNotEmpty(purchaseRequestDO.getDispatcherId())) {
//                    ProfileDO profileDO = profileMapper.itemById(purchaseRequestDO.getDispatcherId());
//                    if (profileDO != null && StringUtils.isNotEmpty(profileDO.getSapCode())) {
//                        if (profileDO != null && companyUtil.ynOrgId().equals(profileDO.getSpaceId())) {
//                            if (StringUtils.isNotEmpty(profileDO.getSapCode())) {
//                                if (profileDO.getSapCode().length() < 8) {
//                                    sendBillHeaderVO.setSalesCode(profileDO.getSapCode() + "6");
//                                } else {
//                                    sendBillHeaderVO.setSalesCode(profileDO.getSapCode());
//                                }
//                            }
//                        } else {
//                            sendBillHeaderVO.setSalesCode(profileDO.getSapCode());
//                        }
//                        sendBillHeaderVO.setSalesName(profileDO.getName());
//                    }
//                }
//            }
//        }
//        sendBillHeaderVO.setReceiveCode("1001");
//        //云内 销售公司编号1006(一般是)
//        sendBillHeaderVO.setSalescompanyCode(sendBillDO.getSalesCode());
//
//        //果直投订单上的代理商结算信息为“昆明公司不参与结算”，则直投订单传输中间表，表头信息的采购公司写入“1006”，销售公司放空值。
//        boolean kunmingSet = (null != first && null != first.getKunmingSettlement() && 1 == first.getKunmingSettlement());
//        if (!kunmingSet) {
//            sendBillHeaderVO.setReceiveCode("1006");
//            sendBillHeaderVO.setSalescompanyCode(null);
//        }
//
//        SendBillInfo sendBillInfo = new SendBillInfo();
//        sendBillInfo.setSendBillHeaderVO(sendBillHeaderVO);
//        sendBillInfo.setSendBillItemVOs(sendBillItemVOs);
//        return sendBillInfo;
//    }

    public ErrorCode generateOrder(String id, String orgId) throws Exception {
        SendBillDO sendBillDO = sendBillMapper.selectByPrimaryKey(id);
        if (sendBillDO == null) {
            return ErrorCode.IllegalArument;
        }
        if(!Integer.valueOf(1).equals(sendBillDO.getSendType())) {
            throw new Exception("非直投用户单据，请走签收扫码入库流程");
        }
        if (!sendBillDO.getApplyOrgId().equals(orgId)) {
            if(companyDealerMapper.findDealerOrgId(orgId,sendBillDO.getApplyOrgId())<=0){
                throw new Exception("只有申请单位允许生成单据");
            }
        }
        if (sendBillDO.getIsGenerateOrder() == 1) {
            throw new Exception("此送货单已经生成单据");
        }
        //送货单是直投属性时自动生成销售意向单、发货通知单、采购入库单
        this.addBySendBill(sendBillDetailMapper.list(id), sendBillDO.getSendOrder());
        sendBillMapper.updateIsGenerateOrder(sendBillDO.getId(), 1);
        return ErrorCode.Success;
    }

    public SendBillAddVO item(String id,String orgId){
        SendBillAddVO result = new SendBillAddVO();
        SendBillDO sendBillDO = sendBillMapper.selectByPrimaryKey(id);
        if(sendBillDO == null){
            return null;
        }
        CompanyInfoDO companyInfoDO=companyInfoMapper.item(orgId);
        if(companyInfoDO==null){
            return result;
        }
        SendBillVO sendBillVO = new SendBillVO();
        BeanUtils.copyProperties(sendBillDO, sendBillVO);
        String companyName = getSupplierName(sendBillVO.getApplyOrgId(), sendBillVO.getDeliveryOrgId(), sendBillVO.getSoldOrgId());
        if(StringUtils.isNotEmpty(companyName) && orgId.equals(sendBillVO.getDeliveryOrgId())) {
            sendBillVO.setSoldOrgName(companyName);
        }
        result.setHeaderInfo(sendBillVO);
        List<SendBillDetailVO> listVO = new ArrayList<>();
        List<SendBillDetailDO> listDO = sendBillDetailMapper.listMore(id);
        BigDecimal totalQuantity = BigDecimal.ZERO;
        for(SendBillDetailDO entity : listDO){
            SendBillDetailVO model = new SendBillDetailVO();
            totalQuantity = totalQuantity.add(entity.getQty()==null?BigDecimal.ZERO:entity.getQty());
            BeanUtils.copyProperties(entity, model);
            PurchaseRequestDetailDO requestDetailDO = purchaseRequestDetailMapper.findByBillIdAndMaterialNo(entity.getSourceId(), entity.getMaterialsNo(), entity.getSourceRowNo());
            if(requestDetailDO != null && !companyInfoDO.getCompanyType().equals(CompanyTypeEnum.Type.Supplier.toString())){
                //供应商不查价格
                model.setPrintPrice(requestDetailDO.getSettlementPrice().divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_DOWN));
            }else {
                model.setPrintPrice(null);
                model.setPrice(null);
                model.setTotalPrice(null);
            }
            if(requestDetailDO != null) {
                model.setTotalQty(requestDetailDO.getQty());
                model.setInformQty(requestDetailDO.getInformQty());
            }
            listVO.add(model);
        }
        sendBillVO.setTotalQuantity(totalQuantity);
        result.setMaterialsList(listVO);
        //查询物流信息列表
        List<DeliveryReceiptLogisticsDO> logisticsDOList = deliveryReceiptLogisticsMapper.list(sendBillDO.getSendOrder());
        List<DeliveryReceiptLogisticsVO> logisticsVOList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(logisticsDOList)){
            logisticsVOList = BeanUtil.do2bo4List(logisticsDOList, DeliveryReceiptLogisticsVO.class);
        }
        result.setLogisticsVOList(logisticsVOList);
        return result;
    }

    public void export(List<String> ids)throws Exception{
        invokeExport(sendBillMapper.findByIds(ids));
    }

    public void exportAll(SendBillVO condition)throws Exception{
        condition.setBillNosList(xcmg.device.infra.StringUtil.splitList(condition.getBillNos()));
        //Integer count = sendBillMapper.listCount(condition);
        List<SendBillDO> dataList =sendBillMapper.list(condition);
//        int times = count/500+1;
//        for(int i=0; i<times; i++){
//            PageHelperPlus.startPage(i+1,500, "create_date desc");
//            dataList.addAll(sendBillMapper.list(condition));
//        }
        invokeExport(dataList);
    }

    private void invokeExport(List<SendBillDO> doList)throws Exception{
        String title = "送货单数据导出";
        String[] rowsName = new String[]{"序号","送货单号","来源单号","收货方","采购单号","零件编码","自定义零件编码",
                "零件名称","数量","收货人", "联系人电话", "地址", "物流公司", "物流单号","是否发货","备注",
                "预计送达时间","单价","总价","是否签收"};
        List<Object[]>  dataList = new ArrayList<>();
        Object[] objs;
        for (int i = 0; i < doList.size(); i++) {
            SendBillDO exportDO = doList.get(i);
            List<SendBillDetailDO> list = sendBillDetailMapper.listMore(exportDO.getId());
            if(ListUtil.isNullOrEmpty(list)){
                continue;
            }
            for(SendBillDetailDO detailDO : list){
                objs = new Object[rowsName.length];
                objs[0] = i+1;
                objs[1] = exportDO.getSendOrder();
                objs[2] = detailDO.getInitialOrder();
                objs[3] = exportDO.getDeliveryOrgName();
                objs[4] = detailDO.getSourceOrder();
                objs[5] = detailDO.getMaterialsNo();
                objs[6] = detailDO.getCustomMaterialsNo();
                objs[7] = detailDO.getMaterialsDes();
                objs[8] = detailDO.getQty();
                objs[9] = exportDO.getContactUser();
                objs[10] = exportDO.getContactTel();
                objs[11] = exportDO.getAddress();
                objs[12] = exportDO.getLogisticsCompany();
                objs[13] = exportDO.getLogisticsOrder();
                objs[14] = exportDO.getIsDelivery()==null?"否":(exportDO.getIsDelivery()==0?"否":"是");
                objs[15] = exportDO.getNote();
                objs[16] = DateUtil.formatDate(exportDO.getDeliveryDate());
                objs[17] = detailDO.getPrice();
                objs[18] = detailDO.getTotalPrice();
                objs[19] = exportDO.getIsSign()==null?"否":(exportDO.getIsSign()==0?"否":"是");
                dataList.add(objs);
            }
        }
        ExportUtil exportUtil = new ExportUtil(title, rowsName, dataList);
        exportUtil.export(response);
    }

    private String getInboundState(Integer state){
        switch (state){
            case 0:
                return "未入库";
            case 1:
                return "部分入库";
            case 2:
                return "已入库";
            default:
                return "未入库";
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean updateByInbound(String backOrder, String materialNo, Integer rowNo, BigDecimal realAmount,
                                   Integer singelState, Integer totalState, String orgId)throws Exception{
        SendBillDO inboundDO = sendBillMapper.findBySendOrder(backOrder, orgId);
        if(inboundDO == null){
            return false;
        }
        List<SendBillDetailDO> detailDOs = sendBillDetailMapper.findByMainIdAndMaterialNo(inboundDO.getId(), materialNo, rowNo);
        if(CollectionUtils.isEmpty(detailDOs)){
            return false;
        }
        
        //if(Integer.valueOf(1).equals(inboundDO.getSendType()) ||detailDOs.size() == 1) {
        SendBillDetailDO detailDO = detailDOs.get(0);
            detailDO.setRealQty(realAmount);
            detailDO.setStatus(singelState);
        boolean success = sendBillDetailMapper.update(detailDO) > 0;
        if (success) {
            inboundDO.setStatus(totalState);
            success = sendBillMapper.update(inboundDO) > 0;
            if (!success) {
                return false;
            }
        }
        return success;
        //}else {
        //for(SendBillDetailDO detailDO: detailDOs) {
        //zstest
        //}
        //return true;
        //}
    }
    
    private void addPurchaseBillBySendBill(List<SendBillDetailDO> list, String sendOrder, Integer sendType) throws Exception {
        if (ListUtil.isNullOrEmpty(list)) {
            return;
        }
        Map<String, List<SendBillDetailDO>> map = new HashMap<>();
        List<SendBillDetailDO> dataList;
        for(SendBillDetailDO detailDO : list){
            if(map.containsKey(detailDO.getSourceId())){
                map.get(detailDO.getSourceId()).add(detailDO);
            }else{
                dataList = new ArrayList<>();
                dataList.add(detailDO);
                map.put(detailDO.getSourceId(), dataList);
            }
        }

        for(String billId : map.keySet()){
            PurchaseRequestDO requestDO = purchaseRequestMapper.item(billId);
            if(requestDO == null){
                throw new Exception("未找到采购申请单");
            }

            //自动生成采购入库单，状态为已入库，自动过账
            // this.addPurchaseInbound(requestDO, map.get(billId), sendOrder);
            //非直投创建采购入库单
            this.addPurchaseInboundBill(requestDO, map.get(billId), sendOrder, sendType);
        }
    }

    private void addBySendBill(List<SendBillDetailDO> list, String sendOrder)throws Exception{
        if(ListUtil.isNullOrEmpty(list)){
            return;
        }
        Map<String, List<SendBillDetailDO>> map = new HashMap<>();
        List<SendBillDetailDO> dataList;
        for(SendBillDetailDO detailDO : list){
            if(map.containsKey(detailDO.getSourceId())){
                map.get(detailDO.getSourceId()).add(detailDO);
            }else{
                dataList = new ArrayList<>();
                dataList.add(detailDO);
                map.put(detailDO.getSourceId(), dataList);
            }
        }

        for(String billId : map.keySet()){
            PurchaseRequestDO requestDO = purchaseRequestMapper.item(billId);
            if(requestDO == null){
                throw new Exception("未找到采购申请单");
            }
            //自动新增销售意向单
            this.addSaleIntention(requestDO, sendOrder);

            //原采购入库单
            PurchaseRequestDO directSourceRequestDO = purchaseRequestMapper.itemByPurchase(requestDO.getDirectSourceOrder(), requestDO.getDeliveryOrgId());
            
            //自动生成采购入库单，状态为已入库，自动过账
            this.addPurchaseInbound(requestDO, map.get(billId), sendOrder, directSourceRequestDO);
            
            //自动生成发货通知单，状态为已出库，自动过账
            this.addDeliveryNote(requestDO, map.get(billId), sendOrder);
        }

    }

    private void addSaleIntention(PurchaseRequestDO request, String sendOrder)throws Exception{
        PurchaseRequestDO requestDO = purchaseRequestMapper.itemByPurchase(request.getDirectSourceOrder(), request.getDeliveryOrgId());
        if(requestDO == null){
            CompanyDealerDO companyDealerDO=companyDealerMapper.itemByDealerCode(request.getPurchaseOrgId(),request.getDeliveryOrgId());
            if(companyDealerDO!=null){
                requestDO = purchaseRequestMapper.itemByPurchase(request.getDirectSourceOrder(), companyDealerDO.getPlatOrgId());
            }
            if(requestDO==null){
                CompanyDealerDO companyDealerDO1=companyDealerMapper.itemByDealerCode(request.getSupplierOrgId(),request.getDeliveryOrgId());
                if(companyDealerDO1!=null){
                    requestDO = purchaseRequestMapper.itemByPurchase(request.getDirectSourceOrder(), companyDealerDO1.getPlatOrgId());
                }
            }
            if(requestDO==null){
                throw new Exception("未找到采购申请单");
            }
        }
        SaleIntentionVO intentionVO = new SaleIntentionVO();
        intentionVO.setSupplierOrgId(requestDO.getSupplierOrgId());
        intentionVO.setPurchaseOrgId(requestDO.getPurchaseOrgId());
        intentionVO.setPurchaseNo(requestDO.getBillNo());
        List<SaleIntentionDO> list = saleIntentionMapper.list(intentionVO);
        if(!ListUtil.isNullOrEmpty(list)){
            SaleIntentionDO intentionDO = list.get(0);
            if (StringUtil.isNullOrEmpty(intentionDO.getSendOrder())) {
                intentionDO.setSendOrder(sendOrder);
            } else {
                intentionDO.setSendOrder(intentionDO.getSendOrder() + "," + sendOrder);
            }
            saleIntentionMapper.update(intentionDO);
            return;
        }
        SaleAddVO model = new SaleAddVO();
        SaleIntentionVO headerInfo = new SaleIntentionVO();
        List<SaleIntentionDetailVO> materialList = new ArrayList<>();

        headerInfo.setDeliverTypeName(requestDO.getShippingMethod());
        headerInfo.setPurchaseLevelId(requestDO.getPurchaseType());
        headerInfo.setPurchaseLevelName(requestDO.getTypeDesc());
        headerInfo.setPurchaseNo(requestDO.getBillNo());
        headerInfo.setPurchaseOrgId(requestDO.getPurchaseOrgId());
        headerInfo.setPurchaseOrgName(requestDO.getPurchaseOrgName());
        headerInfo.setSupplierOrgId(requestDO.getSupplierOrgId());
        headerInfo.setSupplierOrgName(requestDO.getSupplierOrgName());
        headerInfo.setReceiveAddress(requestDO.getReceiverAddress());
        headerInfo.setReceiverFax(requestDO.getReceiverFax());
        headerInfo.setReceiverName(requestDO.getReceiverName());
        headerInfo.setReceiverPhone(requestDO.getReceiverTel());
        headerInfo.setStatus(String.valueOf(SaleStatus.Submit.getCode()));
        headerInfo.setCreatorId(request.getCreateId());
        headerInfo.setCreateName(request.getCreateName());
        headerInfo.setIsDirect(1);
        headerInfo.setCreateType(0);
        headerInfo.setIsSign(1);
        headerInfo.setSignDate(new Date());
        headerInfo.setSendOrder(sendOrder);
        headerInfo.setInventoryOutStatus("2");

        List<PurchaseRequestDetailDO> detailDOList = purchaseRequestDetailMapper.list(requestDO.getBillId());
        if(ListUtil.isNullOrEmpty(detailDOList)){
            throw new Exception("未找到采购单详情记录");
        }
        for(PurchaseRequestDetailDO requestDetailDO : detailDOList){
            SaleIntentionDetailVO detailVO = new SaleIntentionDetailVO();
            detailVO.setMaterialsNo(requestDetailDO.getMaterialsNo());
            detailVO.setMaterialsDes(requestDetailDO.getMaterialsDes());
            detailVO.setUnit(requestDetailDO.getUnit());
            detailVO.setPrice(takeDecimals(requestDetailDO.getPrice()));
            detailVO.setUnitPriceAfterAdjust(takeDecimals(requestDetailDO.getSettlementPrice()));
            detailVO.setApplyTotalPrice(takeDecimals(requestDetailDO.getApplyTotalPrice()));
            detailVO.setTotalPriceAfterAdjust(detailVO.getUnitPriceAfterAdjust().multiply(requestDetailDO.getQty()));
            detailVO.setQty(requestDetailDO.getQty());
            detailVO.setAmountAfterAdjust(requestDetailDO.getQty());
            detailVO.setInformedAmount(BigDecimal.ZERO);
            detailVO.setInventoryOutAmount(BigDecimal.ZERO);
            detailVO.setRequestDeliveryDate(requestDetailDO.getDeliveryDate());
            detailVO.setInventoryOutStatus("0");
            materialList.add(detailVO);
        }
        model.setHeaderInfo(headerInfo);
        model.setMaterialList(materialList);
        saleIntentionService.add(model);
    }
    
    private void addPurchaseInboundBill(PurchaseRequestDO requestDO, List<SendBillDetailDO> sendBillDetailList, String sendOrder, Integer sendType)throws Exception {

        ActionResult dd = authClient.getUserDetail(requestDO.getCreateId());
        PurchaseInboundDO inboundDO = new PurchaseInboundDO();
        inboundDO.setId(fastGenClient.textGuid().getValue());
        inboundDO.setPurchaseInboundOrder(genDocumentService.genDocumentNo(BillDesc.PurchaseInbound, requestDO.getPurchaseOrgId()));
        inboundDO.setPurchaseRequestOrder(requestDO.getBillNo());
        inboundDO.setSupplierOrgId(requestDO.getSupplierOrgId());
        inboundDO.setSupplierName(requestDO.getSupplierOrgName());
        inboundDO.setOrgId(requestDO.getPurchaseOrgId());
        if(dd != null){
            UserCacheDTO userInfo = (UserCacheDTO) dd.getValue();
            inboundDO.setDeptId(userInfo.getDeptId());
            inboundDO.setDeptName(userInfo.getDeptName());
            inboundDO.setCreateId(requestDO.getCreateId());
            inboundDO.setCreateName(userInfo.getName());
        }
        inboundDO.setCreateDate(new Date());

        if(Integer.valueOf(1).equals(sendType)) {
            WarehouseAreaDO areaDO = warehouseAreaDOMapper.findDirectArea(requestDO.getPurchaseOrgId());
            if (areaDO == null || StringUtil.isNullOrEmpty(areaDO.getAreaCode()) || StringUtil.isNullOrEmpty(areaDO.getWarehouseCode())) {
                // throw new Exception("未找到默认直投库区");
                areaDO = createNewDirectArea(requestDO.getPurchaseOrgId());
            }
            if (areaDO != null) {
                inboundDO.setWarehouseCode(areaDO.getWarehouseCode());
                inboundDO.setInArea(areaDO.getAreaCode());
                inboundDO.setSapInArea(areaDO.getSapCode());
            }
        }else {
            WarehouseAreaDO areaDO = warehouseAreaDOMapper.getInfoByArea(requestDO.getPurchaseOrgId(), requestDO.getSapInArea());
            if (areaDO == null) {
                areaDO = warehouseAreaDOMapper.findDirectArea(requestDO.getPurchaseOrgId());
            }
            if (areaDO == null || StringUtil.isNullOrEmpty(areaDO.getAreaCode()) || StringUtil.isNullOrEmpty(areaDO.getWarehouseCode())) {
                throw new Exception("采购库区不存在");
            }
            if (areaDO != null) {
                inboundDO.setWarehouseCode(areaDO.getWarehouseCode());
                inboundDO.setInArea(areaDO.getAreaCode());
                inboundDO.setSapInArea(areaDO.getSapCode());
            }
        }
        inboundDO.setStatus(0);
        inboundDO.setSendOrder(sendOrder);
        boolean success = purchaseInboundMapper.insert(inboundDO)>0;
        if(!success){
            throw new Exception("生成采购入库单失败");
        }
        String orgId = inboundDO.getOrgId();
        for(SendBillDetailDO sendBillDetailDO : sendBillDetailList){
            PurchaseRequestDetailDO requestDetailDO = purchaseRequestDetailMapper.findByBillIdAndMaterialNo(requestDO.getBillId(), sendBillDetailDO.getMaterialsNo(), null);
            if(requestDetailDO == null){
                throw new Exception("未找到采购单详情记录");
            }
            PurchaseInboundDetailDO inboundDetailDO = new PurchaseInboundDetailDO();
            inboundDetailDO.setId(fastGenClient.textGuid().getValue());
            inboundDetailDO.setPurchaseInboundOrder(inboundDO.getPurchaseInboundOrder());
            inboundDetailDO.setMaterialNo(sendBillDetailDO.getMaterialsNo());
            inboundDetailDO.setMaterialName(sendBillDetailDO.getMaterialsDes());
            inboundDetailDO.setMaterialType(sendBillDetailDO.getMaterialsType());
            inboundDetailDO.setUnit(sendBillDetailDO.getUnit());
            inboundDetailDO.setQty(requestDetailDO.getQty());
            inboundDetailDO.setSendQty(requestDetailDO.getSendQty().add(sendBillDetailDO.getQty()));
            inboundDetailDO.setAmount(sendBillDetailDO.getQty());
            inboundDetailDO.setRealAmount(BigDecimal.ZERO);
            inboundDetailDO.setStatus(0);
            inboundDetailDO.setPrice(requestDetailDO.getSettlementPrice().divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP));
            inboundDetailDO.setTotalPrice(inboundDetailDO.getPrice().multiply(inboundDetailDO.getAmount()));
            inboundDetailDO.setCreateId(inboundDO.getCreateId());
            inboundDetailDO.setCreateName(inboundDO.getCreateName());
            inboundDetailDO.setCreateDate(inboundDO.getCreateDate());
            inboundDetailDO.setOrgId(orgId);
            inboundDetailDO.setRowNo(requestDetailDO.getRowNo());
            success = purchaseInboundDetailMapper.insert(inboundDetailDO)>0;
            if(!success){
                throw new Exception("生成采购入库单详情记录失败");
            }

            //更新其他采购入库单的已入库意向数量
            purchaseInboundDetailMapper.updateSendQty(orgId, inboundDetailDO.getSendQty(),
                    inboundDO.getPurchaseRequestOrder(), inboundDetailDO.getMaterialNo());

            //更新采购申请详情入库意向数量
            purchaseRequestService.updateSendQty(inboundDO.getPurchaseRequestOrder(), inboundDetailDO.getMaterialNo(),
                    inboundDetailDO.getSendQty(), inboundDetailDO.getRowNo(), orgId);
        }
    }

    private WarehouseAreaDO createNewDirectArea(String orgId) {
        WarehouseDO warehouseDO = insertDirectWarehouse(orgId);
        WarehouseAreaDO areaDO = insertDirectArea(warehouseDO.getId(), orgId);
        insertLocation(areaDO.getId(), orgId);
        return areaDO;
    }
    
    private void insertLocation(String areaId, String orgId) {
        WarehouseAreaLocationDO locationDO = new WarehouseAreaLocationDO();
        locationDO.setLocationCode("DIREACT_AREA_LOCATION");
        locationDO.setWarehouseAreaId(areaId);
        String first = "1";
        locationDO.setRowNo(first);
        locationDO.setFloorNo(first);
        locationDO.setColumnNo(first);
        locationDO.setSeqNo(first);
        locationDO.setShelfType("默认");
        locationDO.setShelfNo("默认");
        locationDO.setOrgId(orgId);
        locationDO.setLocationDesc("默认直投库区");
        locationDO.setCreateTime(new Date());
        warehouseAreaLocationDOMapper.insert(locationDO);
    }
    
    private WarehouseAreaDO insertDirectArea(String warehouseId, String orgId) {
        WarehouseAreaDO warehouseAreaDO = new WarehouseAreaDO();
        warehouseAreaDO.setId(fastGenClient.textGuid().getValue());
        warehouseAreaDO.setAreaCode("DIRECT_DEFAULT_AREA");
        warehouseAreaDO.setWarehouseId(warehouseId);
        warehouseAreaDO.setAttrId(null);
        warehouseAreaDO.setAttrDesc(null);
        warehouseAreaDO.setDescription("默认直投库区");
        warehouseAreaDO.setSapCode(null);
        warehouseAreaDO.setOrgId(orgId);
        warehouseAreaDO.setIsDirect(1);
        warehouseAreaDOMapper.insertDirect(warehouseAreaDO);
        return warehouseAreaDO;
    }
    
    private WarehouseDO insertDirectWarehouse(String orgId) {
        WarehouseDO warehouseDO = new WarehouseDO();
        warehouseDO.setId(fastGenClient.textGuid().getValue());;
        warehouseDO.setWarehouseCode("DIRECT_DEFAULT");
        warehouseDO.setOrgId(orgId);
        warehouseDO.setDescription("默认直投仓库");
        warehouseDO.setKeeperId(null);
        warehouseDO.setIsPlan(0);
        warehouseDO.setIsCenter(0);
        warehouseDO.setFirstInOut(0);
        warehouseDO.setIsBarCode(1);
        warehouseDO.setWarehouseType(null);
        warehouseDO.setWarehouseTypeDesc("默认直投仓库");
        warehouseDOMapper.insert(warehouseDO);
        return warehouseDO;
    }
    
    private void addPurchaseInbound(PurchaseRequestDO requestDO, List<SendBillDetailDO> sendBillDetailList, String sendOrder, PurchaseRequestDO sourcePurchaseRequestDO)throws Exception{
        WarehouseAreaDO areaDO = warehouseAreaDOMapper.findDirectArea(requestDO.getPurchaseOrgId());
        if(areaDO == null || StringUtil.isNullOrEmpty(areaDO.getAreaCode()) || StringUtil.isNullOrEmpty(areaDO.getWarehouseCode())){
            // throw new Exception("未找到默认直投库区");
            areaDO = createNewDirectArea(requestDO.getPurchaseOrgId());
        }
        ActionResult dd = authClient.getUserDetail(requestDO.getCreateId());
        PurchaseInboundDO inboundDO = new PurchaseInboundDO();
        inboundDO.setId(fastGenClient.textGuid().getValue());
        inboundDO.setPurchaseInboundOrder(genDocumentService.genDocumentNo(BillDesc.PurchaseInbound, requestDO.getPurchaseOrgId()));
        inboundDO.setPurchaseRequestOrder(requestDO.getBillNo());
        inboundDO.setSupplierOrgId(requestDO.getSupplierOrgId());
        inboundDO.setSupplierName(requestDO.getSupplierOrgName());
        inboundDO.setOrgId(requestDO.getPurchaseOrgId());
        if(dd != null){
            UserCacheDTO userInfo = (UserCacheDTO) dd.getValue();
            inboundDO.setDeptId(userInfo.getDeptId());
            inboundDO.setDeptName(userInfo.getDeptName());
            inboundDO.setCreateId(requestDO.getCreateId());
            inboundDO.setCreateName(userInfo.getName());
        }
        inboundDO.setCreateDate(new Date());
        inboundDO.setWarehouseCode(areaDO.getWarehouseCode());
        inboundDO.setInArea(areaDO.getAreaCode());
        inboundDO.setSapInArea(areaDO.getSapCode());
        inboundDO.setStatus(2);
        inboundDO.setSendOrder(sendOrder);
        boolean success = purchaseInboundMapper.insert(inboundDO)>0;
        if(!success){
            throw new Exception("生成采购入库单失败");
        }
        String orgId = inboundDO.getOrgId();
        for(SendBillDetailDO sendBillDetailDO : sendBillDetailList){
            PurchaseRequestDetailDO requestDetailDO = purchaseRequestDetailMapper.findByBillIdAndMaterialNo(requestDO.getBillId(), sendBillDetailDO.getMaterialsNo(), null);
            if(requestDetailDO == null){
                throw new Exception("未找到采购单详情记录");
            }
            PurchaseInboundDetailDO inboundDetailDO = new PurchaseInboundDetailDO();
            inboundDetailDO.setId(fastGenClient.textGuid().getValue());
            inboundDetailDO.setPurchaseInboundOrder(inboundDO.getPurchaseInboundOrder());
            inboundDetailDO.setMaterialNo(sendBillDetailDO.getMaterialsNo());
            inboundDetailDO.setMaterialName(sendBillDetailDO.getMaterialsDes());
            inboundDetailDO.setMaterialType(sendBillDetailDO.getMaterialsType());
            inboundDetailDO.setUnit(sendBillDetailDO.getUnit());
            inboundDetailDO.setQty(requestDetailDO.getQty());
            inboundDetailDO.setSendQty(requestDetailDO.getSendQty().add(sendBillDetailDO.getQty()));
            inboundDetailDO.setAmount(sendBillDetailDO.getQty());
            inboundDetailDO.setRealAmount(sendBillDetailDO.getQty());
            inboundDetailDO.setStatus(2);
            inboundDetailDO.setPrice(requestDetailDO.getSettlementPrice().divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP));
            inboundDetailDO.setTotalPrice(inboundDetailDO.getPrice().multiply(inboundDetailDO.getAmount()));
            inboundDetailDO.setCreateId(inboundDO.getCreateId());
            inboundDetailDO.setCreateName(inboundDO.getCreateName());
            inboundDetailDO.setCreateDate(inboundDO.getCreateDate());
            inboundDetailDO.setOrgId(orgId);
            inboundDetailDO.setRowNo(requestDetailDO.getRowNo());
            success = purchaseInboundDetailMapper.insert(inboundDetailDO)>0;
            if(!success){
                throw new Exception("生成采购入库单详情记录失败");
            }

            //更新其他采购入库单的已入库意向数量
            purchaseInboundDetailMapper.updateSendQty(orgId, inboundDetailDO.getSendQty(),
                    inboundDO.getPurchaseRequestOrder(), inboundDetailDO.getMaterialNo());

            //更新采购申请详情入库意向数量
            purchaseRequestService.updateSendQty(inboundDO.getPurchaseRequestOrder(), inboundDetailDO.getMaterialNo(),
                    inboundDetailDO.getSendQty(), inboundDetailDO.getRowNo(), orgId);

            if (sourcePurchaseRequestDO != null) {
                purchaseRequestService.updateSourceSendQty(sourcePurchaseRequestDO, inboundDetailDO.getMaterialNo(),
                        inboundDetailDO.getSendQty(), inboundDetailDO.getRowNo());
            }
        }
//        //调用采购凭证收货接口
//        if(!StringUtil.isNullOrEmpty(requestDO.getVoucherNo())){
//            purchaseInboundService.sapPostForSendBill(inboundDO.getId(), orgId);
//        }
    }

    private void addDeliveryNote(PurchaseRequestDO request, List<SendBillDetailDO> sendBillDetailList, String sendOrder)throws Exception{
        PurchaseRequestDO requestDO = purchaseRequestMapper.itemByPurchase(request.getDirectSourceOrder(), request.getDeliveryOrgId());
        if(requestDO == null){
            throw new Exception("未找到采购申请单");
        }
        SaleIntentionDO saleIntentionDO = saleIntentionMapper.itemByPurchaseNo(requestDO.getBillNo(), requestDO.getSupplierOrgId());
        if(saleIntentionDO == null){
            throw new Exception("未找到销售意向单");
        }
        WarehouseAreaDO areaDO = warehouseAreaDOMapper.findDirectArea(requestDO.getSupplierOrgId());
        if(areaDO == null || StringUtil.isNullOrEmpty(areaDO.getAreaCode()) || StringUtil.isNullOrEmpty(areaDO.getWarehouseCode())){
            // throw new Exception("未找到默认直投库区");
            areaDO = createNewDirectArea(requestDO.getSupplierOrgId());
        }
        DeliveryNoteAddVO noteAddVO = new DeliveryNoteAddVO();
        DeliveryNoteVO headerInfo = new DeliveryNoteVO();
        List<DeliveryNoteDetailVO> materialList = new ArrayList<>();

        headerInfo.setAddress(requestDO.getReceiverAddress());
        headerInfo.setDeliveryTypeName(requestDO.getShippingMethod());
        headerInfo.setDistributionChannelName("内销");
        headerInfo.setOutArea(areaDO.getWarehouseCode());
        headerInfo.setOutLocation(areaDO.getAreaCode());
        headerInfo.setSapOutArea(areaDO.getSapCode());
        headerInfo.setPayConditionName("全款提货");
        headerInfo.setPurchaseLevelId(requestDO.getPurchaseType());
        headerInfo.setPurchaseLevelName(requestDO.getTypeDesc());
        headerInfo.setPurchaseOrgId(requestDO.getPurchaseOrgId());
        headerInfo.setPurchaseOrgName(requestDO.getPurchaseOrgName());
        headerInfo.setReceiverName(requestDO.getReceiverName());
        headerInfo.setReceiverFax(requestDO.getReceiverFax());
        headerInfo.setReceiverPhone(requestDO.getReceiverTel());
        headerInfo.setSaleNo(saleIntentionDO.getSaleNo());
        headerInfo.setSettleTypeName("寄付");
        headerInfo.setCreatorId(saleIntentionDO.getCreatorId());
        headerInfo.setCreateName(saleIntentionDO.getCreateName());
        headerInfo.setSupplierOrgId(saleIntentionDO.getSupplierOrgId());
        headerInfo.setSupplierOrgName(saleIntentionDO.getSupplierOrgName());
        headerInfo.setStatus(String.valueOf(DeliveryStatus.Submit.getCode()));
        headerInfo.setIsSign(1);
        headerInfo.setSignDate(new Date());
        headerInfo.setSendOrder(sendOrder);

        for(SendBillDetailDO sendBillDetailDO : sendBillDetailList){
            SaleIntentionDetailDO intentionDetailDO = saleIntentionDetailMapper.findBySaleIntentionIdAndMaterialsNo(saleIntentionDO.getId(), sendBillDetailDO.getMaterialsNo());
            if(intentionDetailDO == null){
                throw new Exception("未找到销售意向详情");
            }
            DeliveryNoteDetailVO noteDetailVO = new DeliveryNoteDetailVO();
            BeanUtils.copyProperties(intentionDetailDO, noteDetailVO);
            noteDetailVO.setSendQty(intentionDetailDO.getInformedAmount());
            noteDetailVO.setDeliveryQty(sendBillDetailDO.getQty());
            noteDetailVO.setPrice(takeDecimals(noteDetailVO.getPrice()));
            noteDetailVO.setApplyTotalPrice(takeDecimals(noteDetailVO.getApplyTotalPrice()));
            noteDetailVO.setUnitPriceAfterAdjust(takeDecimals(noteDetailVO.getUnitPriceAfterAdjust()));
            noteDetailVO.setTotalPriceAfterAdjust(takeDecimals(noteDetailVO.getTotalPriceAfterAdjust()));
            materialList.add(noteDetailVO);
        }

        noteAddVO.setHeaderInfo(headerInfo);
        noteAddVO.setMaterialList(materialList);
        deliveryNoteService.addBySendBill(noteAddVO, headerInfo.getSupplierOrgId());
    }

    private static BigDecimal takeDecimals(BigDecimal price) {
        if (price == null) {
            return BigDecimal.ZERO;
        }
        return price.divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
    }

//    public ErrorCode sapPost(String id, String orgId) throws Exception {
//        SendBillDetailDO sendBillDetailDO = sendBillDetailMapper.selectByPrimaryKey(id);
//        if(sendBillDetailDO == null){
//            throw new Exception("未找到详情记录");
//        }
//        SendBillDO sendBillDO = sendBillMapper.selectByPrimaryKey(sendBillDetailDO.getMainId());
//        if(sendBillDO == null){
//            throw new Exception("未找到送货单");
//        }
//        if(sendBillDO.getSendType() == 1){
//            throw new Exception("直投送货单不能过账");
//        }
//        PurchaseRequestDO requestDO = purchaseRequestMapper.item(sendBillDetailDO.getSourceId());
//        if(requestDO == null){
//            throw new Exception("未找到来源采购单");
//        }
//        if(StringUtil.isNullOrEmpty(requestDO.getVoucherNo())){
//            throw new Exception("来源采购单尚未同步");
//        }
//        if(sendBillDetailDO.getPostingState() == 2){
//            throw new Exception("该送货单已过账");
//        }
//        if(sendBillDetailDO.getRealQty().compareTo(BigDecimal.ZERO) == 0){
//            throw new Exception("该送货单尚未入库");
//        }
//        if(sendBillDetailDO.getRealQty().compareTo(sendBillDetailDO.getPostingNum()) == 0){
//            throw new Exception("已入库数量都已经过账");
//        }
//
//        ImportParam importParam = new ImportParam();
//        importParam.setFunction("ZPMSBJ_SET_MIGOE");
//        importParam.setTable("ZWJBJ_MIGOE");
//        BigDecimal postQty = sendBillDetailDO.getRealQty().subtract(sendBillDetailDO.getPostingNum());
//        Map<String, List<Map<String, String>>> tableParamMap = new HashMap<>();
//
//        List<Map<String, String>> dataList = new ArrayList<>();
//        Map<String, String> detailMap = new HashMap<>();
//        detailMap.put("EBELN", requestDO.getVoucherNo());
//        detailMap.put("EBELP", sendBillDetailDO.getSourceRowNo()+"");
//        detailMap.put("BWART", "101");
//        detailMap.put("MENGE", postQty+"");
//        List<WarehouseAreaDO> areaList = warehouseInboundRecordMapper.getSapCodeByNo(orgId, sendBillDO.getSendOrder(), sendBillDetailDO.getMaterialsNo());
//        if(ListUtil.isNullOrEmpty(areaList)){
//            throw new Exception("该零件无出入库记录或此入库库区未设置sap编码");
//        }
//        detailMap.put("LGORT", areaList.get(0).getSapCode());
//        dataList.add(detailMap);
//        tableParamMap.put("ZWJBJ_MIGOE", dataList);
//        importParam.setTableParamMap(tableParamMap);
//
//        CompanyInfoDO companyInfo = companyInfoMapper.item(orgId);
//        if (null == companyInfo) {
//            throw new Exception("未查询到企业信息，orgId: " + orgId);
//        }
//        importParam.setSapCode(companyInfo.getSapCode());
//        LogHelper.monitor("========送货单调用采购凭证收货接口开始========");
//        OutputParam outputParam = SAPCommonUtil.getData(importParam);
//        LogHelper.monitor("========送货单调用采购凭证收货接口结束========");
//        if (null == outputParam || outputParam.getCode() != 0) {
//            LogHelper.error("sap返回值为null", ErrorCode.RequestIdError.getCode());
//            throw new Exception("sap返回值为null");
//        }
//        if(ListUtil.isNullOrEmpty(outputParam.getDataList())){
//            LogHelper.error("sap返回值为null", ErrorCode.RequestIdError.getCode());
//            throw new Exception("sap返回值为null");
//        }
//
//        Map<String, String> dataMap = outputParam.getDataList().get(0);
//        if ("OK".equals(dataMap.get("RETURNCODE").toUpperCase())) {
//            if(StringUtil.isNullOrEmpty(dataMap.get("MBLNR"))){
//                throw new Exception("零件凭证编号为null");
//            }
//            sendBillDetailDO.setPostingNum(sendBillDetailDO.getPostingNum().add(postQty));
//            sendBillDetailDO.setVoucherNo(dataMap.get("MBLNR"));
//            if(sendBillDetailDO.getQty().compareTo(sendBillDetailDO.getPostingNum()) == 0){
//                sendBillDetailDO.setPostingState(2);
//                sendBillDetailDO.setPostDate(new Date());
//            }else{
//                sendBillDetailDO.setPostingState(1);
//            }
//            boolean success = sendBillDetailMapper.update(sendBillDetailDO) > 0;
//            if(!success) {
//                throw new Exception("更新凭证编号失败");
//            }
//
//            //过账成功，删除过账失败记录
//            sappostErrorRecordService.updateInsDel(sendBillDO.getSendOrder(), orgId, sendBillDetailDO.getMaterialsNo(), sendBillDetailDO.getRowNo());
//        } else {
//            sendBillDetailDO.setSapErrorMsg(dataMap.get("RETURNMSG"));
//            sendBillDetailMapper.update(sendBillDetailDO);
//
//            SappostErrorRecordDO sappostErrorRecordDO=new SappostErrorRecordDO();
//            sappostErrorRecordDO.setBusinessNo(sendBillDO.getSendOrder());
//            sappostErrorRecordDO.setErrorMessage(dataMap.get("RETURNMSG"));
//            sappostErrorRecordDO.setOrgId(orgId);
//            sappostErrorRecordDO.setMaterialNo(sendBillDetailDO.getMaterialsNo());
//            sappostErrorRecordDO.setRowNo(sendBillDetailDO.getRowNo());
//            sappostErrorRecordDO.setOrderCreateId(sendBillDO.getCreateId());
//            sappostErrorRecordDO.setOrderCreateName(sendBillDO.getCreateName());
//
//            sappostErrorRecordService.add(sappostErrorRecordDO);
//
//            throw new Exception(dataMap.get("RETURNMSG"));
//        }
//        return ErrorCode.Success;
//    }

    //同步成交单价
    @Transactional(rollbackFor = Exception.class)
    public ErrorCode syncSettlementPrice(String id, String orgId) throws Exception {
        SendBillDO sendBillDO = sendBillMapper.selectByPrimaryKey(id);
        if (sendBillDO == null) {
            return ErrorCode.IllegalArument;
        }

        if (null == sendBillDO.getSendType() || sendBillDO.getSendType() == 0) {
            throw new Exception("只有直投订单方可同步价格");
        }

        String applyOrgId = sendBillDO.getApplyOrgId();//申请企业-主机厂

        //查询送货单详情
        List<SendBillDetailDO> detailDOList = sendBillDetailMapper.list(id);
        if (CollectionUtils.isEmpty(detailDOList)){
            throw new Exception("送货单详情不能为空");
        }
        List<String> materialsNos = detailDOList.stream().map(SendBillDetailDO::getMaterialsNo).distinct().collect(Collectors.toList());
        //查询原始采购单据
        List<String> purchaseRequestNos = detailDOList.stream().map(SendBillDetailDO::getInitialOrder).distinct().collect(Collectors.toList());
        PurchaseRequestVO requestVO = new PurchaseRequestVO();
        requestVO.setBillNosList(purchaseRequestNos);
        List<PurchaseRequestDO> requestDOS = purchaseRequestMapper.list(requestVO);
        List<String> purchaseRequestIds = requestDOS.stream().map(PurchaseRequestDO::getBillId).distinct().collect(Collectors.toList());

        List<PurchaseRequestDetailDO> requestDetailDOS = purchaseRequestDetailMapper.listByBIllIds(purchaseRequestIds);

        //查询关联的全部价格方案
        List<String> pirceSchemeIds = requestDetailDOS.stream().filter(detailDO -> detailDO.getPriceSchemeId()!=null)
                .map(PurchaseRequestDetailDO::getPriceSchemeId).distinct().collect(Collectors.toList());
        MarketingActivityVO marketingActivityVO = new MarketingActivityVO();
        marketingActivityVO.setOrgId(applyOrgId);//主机厂
        if (CollectionUtils.isEmpty(pirceSchemeIds)){
            pirceSchemeIds.add("-1");
        }
        marketingActivityVO.setIdList(pirceSchemeIds);
        List<MarketingActivityDO> priceSchemaList = marketingActivityMapper.list(marketingActivityVO);
        Map<String,MarketingActivityDO> priceSchemeMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(priceSchemaList)){
            priceSchemeMap = priceSchemaList.stream().collect(Collectors.toMap(MarketingActivityDO::getId, Function.identity(),(k1,k2)->k2));
        }

        //查询关联的全部零件
        MaterialsSearchVO materialsSearchVO = new MaterialsSearchVO();
        materialsSearchVO.setOrgId(applyOrgId);//申请企业
        materialsSearchVO.setMaterialsList(materialsNos);
        List<MaterialsVO> priMaterialsDOS = priMaterialsMapper.listByMaterialsNos(materialsSearchVO);
        Map<String,MaterialsVO> materialsVOMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(priMaterialsDOS)){
            materialsVOMap = priMaterialsDOS.stream().collect(Collectors.toMap(MaterialsVO::getMaterialsNo, Function.identity(),(k1,k2)->k2));
        }

        //遍历详情
        for (PurchaseRequestDetailDO requestDetailDO : requestDetailDOS){
            String materialsNo = requestDetailDO.getMaterialsNo();
            String schemeId = requestDetailDO.getPriceSchemeId();
            BigDecimal settlementPrice = BigDecimal.ZERO;
            if (materialsNos.contains(materialsNo) && materialsVOMap.containsKey(materialsNo)){
                MaterialsVO materialsVO = materialsVOMap.get(materialsNo);
                BigDecimal salePrice = materialsVO.getPrice() == null ? BigDecimal.ZERO : materialsVO.getPrice();//销售价
                BigDecimal standardPrice = materialsVO.getStandardPrice() == null ? BigDecimal.ZERO : materialsVO.getStandardPrice();//标准价
                if (StringUtils.isNotEmpty(schemeId) && priceSchemeMap.containsKey(schemeId)){
                    MarketingActivityDO marketingActivityDO = priceSchemeMap.get(schemeId);
                    if (marketingActivityDO.getModeType() == 1){//指定价格
                        //查询方案零件表
                        MarketingMaterialsVO marketingMaterialsVO = marketingMaterialsMapper.itemByActivityMaterials(applyOrgId, materialsNo, schemeId);
                        if (null != marketingMaterialsVO){
                            settlementPrice = marketingMaterialsVO.getPrice() == null ? BigDecimal.ZERO : marketingMaterialsVO.getPrice();
                        }else{
                            throw new Exception("零件【"+materialsNo+"】价格方案中指定价格未设置");
                        }

                    }else{
                        BigDecimal modelRate = marketingActivityDO.getModeRate() == null ? BigDecimal.ZERO : marketingActivityDO.getModeRate();
                        // 价格类型为空或者销售价，则调整后价格=销售价*折扣
                        if (StringUtils.isEmpty(marketingActivityDO.getPriceType())
                                || marketingActivityDO.getPriceType().equals(ConstantInfo.PRICE_TYPE_SALE)){
                            settlementPrice = salePrice.multiply(modelRate);
                        }else{//价格类型为空或者销售价，则调整后价格=标准价*折扣
                            settlementPrice = standardPrice.multiply(modelRate);
                        }
                    }
                }else{
                    settlementPrice = salePrice;
                }
            }
            //更新价格
            requestDetailDO.setSettlementPrice(settlementPrice);
            requestDetailDO.setApplyTotalPrice(settlementPrice.multiply(requestDetailDO.getQty()));
            boolean success = purchaseRequestDetailMapper.update(requestDetailDO) > 0;
            if (!success){
                throw new Exception("更新零件【"+materialsNo+"】成交价格失败");
            }

        }

        return ErrorCode.Success;
    }

    public BigDecimal getPrice(String backOrder, String materialNo, String orgId)throws Exception{
        SendBillDO inboundDO = sendBillMapper.findBySendOrder(backOrder, orgId);
        if(inboundDO == null){
            return null;
        }
        return sendBillDetailMapper.getPrice(inboundDO.getId(),materialNo);
    }
    
    public SendBillDO findBySendOrder(String sendOrder, String orgId) {
        return sendBillMapper.findBySendOrder(sendOrder, orgId);
    }
    
//    public void setPullErpSendBillRecord() throws Exception {
//        TaskRecordDO taskRecordDO = new TaskRecordDO();
//        taskRecordDO.setId(fastGenClient.textGuid().getValue());
//        taskRecordDO.setType(String.valueOf(TaskRecordEnum.PULL_SEND_BILL.getCode()));
//        taskRecordDO.setTypeName(TaskRecordEnum.PULL_SEND_BILL.getDesc());
//        taskRecordDO.setTime(new Date());
//        taskRecordMapper.insert(taskRecordDO);
//    }
//
//    public void setPullErpBlRecord() throws Exception {
//        TaskRecordDO taskRecordDO = new TaskRecordDO();
//        taskRecordDO.setId(fastGenClient.textGuid().getValue());
//        taskRecordDO.setType(String.valueOf(TaskRecordEnum.PULL_BL_BILL.getCode()));
//        taskRecordDO.setTypeName(TaskRecordEnum.PULL_BL_BILL.getDesc());
//        taskRecordDO.setTime(new Date());
//        taskRecordMapper.insert(taskRecordDO);
//    }
//
//    public void manualPullSendInfos(SendBillPullCondition sendBillPullCondition) throws Exception {
//        if (Integer.valueOf(1).equals(sendBillPullCondition.getResetFlag())) {
//            if (sendBillPullCondition.getResetStartTime() == null || sendBillPullCondition.getResetEndTime() == null) {
//                throw new Exception("重置起始时间或重置结束时间不能为空");
//            }
//            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//            try {
//                format.parse(sendBillPullCondition.getResetStartTime());
//                format.parse(sendBillPullCondition.getResetEndTime());
//            } catch (Exception e) {
//                throw new Exception("重置起始时间或重置结束时间格式不正确，正确格式为：yyyy-MM-dd");
//            }
//            resetReadFlag(sendBillPullCondition);
//            pullErpSendBillInfos();
//        } else {
//            pullErpSendBillInfos();
//        }
//    }
//
//    public void manualPullBlInfos(SendBillPullCondition sendBillPullCondition) throws Exception {
//        if (Integer.valueOf(1).equals(sendBillPullCondition.getResetFlag())) {
//            if (sendBillPullCondition.getResetStartTime() == null || sendBillPullCondition.getResetEndTime() == null) {
//                throw new Exception("重置起始时间或重置结束时间不能为空");
//            }
//            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//            try {
//                format.parse(sendBillPullCondition.getResetStartTime());
//                format.parse(sendBillPullCondition.getResetEndTime());
//            } catch (Exception e) {
//                throw new Exception("重置起始时间或重置结束时间格式不正确，正确格式为：yyyy-MM-dd");
//            }
//            resetBlReadFlag(sendBillPullCondition);
//            pullBlInfos();
//        } else {
//            pullBlInfos();
//        }
//    }
    
//    private void resetReadFlag(SendBillPullCondition sendBillPullCondition) {
//        ResetTimeConditionVO resetTimeConditionVO = new ResetTimeConditionVO();
//        resetTimeConditionVO.setResetStartTime(sendBillPullCondition.getResetStartTime());
//        resetTimeConditionVO.setResetEndTime(sendBillPullCondition.getResetEndTime());
//        resetTimeConditionVO.setType("3");
//        erpSyncClient.resetReadFlag(resetTimeConditionVO);
//    }
//
//    private void resetBlReadFlag(SendBillPullCondition sendBillPullCondition) {
//        ResetTimeConditionVO resetTimeConditionVO = new ResetTimeConditionVO();
//        resetTimeConditionVO.setResetStartTime(sendBillPullCondition.getResetStartTime());
//        resetTimeConditionVO.setResetEndTime(sendBillPullCondition.getResetEndTime());
//        resetTimeConditionVO.setType("5");
//        erpSyncClient.resetReadFlag(resetTimeConditionVO);
//    }
//
//    @Transactional(rollbackFor = Exception.class)
//    public void pullBlInfos() throws Exception {
//        CompanyInfoDO companyInfoDO = companyInfoMapper.item(companyUtil.ynOrgId());
//        //erpSyncClient.pullBlInfoCount();
//        ActionResult<Object> result = erpSyncClient.pullBlInfoCount();
//        if (ErrorCode.Success.getCode() == result.getCode()) {
//            Integer count = (Integer) result.getValue();
//            if (count != null && count > 0) {
//                int sum = count / 50;
//                int lastSum = count % 50;
//                if (sum > 0) {
//                    for (int i = 0; i < sum; i++) {
//                        processBlInfos((i * 50), (i + 1) * 50, companyInfoDO);
//                    }
//                }
//                if (lastSum > 0) {
//                    processBlInfos(sum * 50, sum * 50 + lastSum, companyInfoDO);
//                }
//            }
//        }
//        pullErpBlDetailInfos();
//    }
//
//    private void processBlInfos(Integer start, Integer end, CompanyInfoDO companyInfoDO) throws Exception {
//        ActionResult<List<BlInfo>> result = erpSyncClient.pullBlInfos(start, end);
//        if (ErrorCode.Success.getCode() != result.getCode()) {
//            throw new Exception("拉取异常");
//        }
//        List<BlInfo> blInfos = result.getValue();
//        List<BlInfo> syncInfos = new ArrayList<BlInfo>();
//        if (CollectionUtils.isNotEmpty(blInfos)) {
//            for (BlInfo blInfo : blInfos) {
//                try {
//                    SendBillInfoDO sendBillInfoDO = convertBlToSendBillInfo(blInfo, companyInfoDO);
//                    sendBillMapper.mergeInto(sendBillInfoDO.getSendBillDO());
//
//                    List<SendBillDetailDO> sendBillDetailDOs = sendBillInfoDO.getSendBillDetailDOs();
//                    for (SendBillDetailDO sendBillDetailDO : sendBillDetailDOs) {
//                        sendBillDetailMapper.mergeInto(sendBillDetailDO);
//                        purchaseRequestDetailMapper.updateInformQty(sendBillDetailDO.getSourceId(), sendBillDetailDO.getMaterialsNo(), sendBillDetailDO.getSourceRowNo(), sendBillDetailDO.getRealQty());
//                        Integer state = 2;
//                        purchaseRequestMapper.updateSendStatus(sendBillDetailDO.getSourceId(), state);
//                    }
//
//                    SendBillAddVO sendBillAddVO = item(sendBillInfoDO.getSendBillDO().getId(), companyUtil.ynOrgId());
//
//                    if (sendBillAddVO != null) {
//                        SendBillDO sendBillDO = sendBillInfoDO.getSendBillDO();
//                        WarehouseInboundDO warehouseInboundDO = warehouseInboundService.getByOrder(sendBillDO.getSendOrder(), companyUtil.ynOrgId());
//                        if (warehouseInboundDO != null) {
//                            warehouseInboundService.deleteByOrder(warehouseInboundDO.getBusinessOrder(), sendBillDO.getDeliveryOrgId());
//                        }
//                        warehouseInboundService.saveBySendBill(sendBillAddVO, sendBillDO.getCreateId(),
//                                sendBillDO.getDeliveryOrgId(), sendBillDO.getApplyOrgId(), 1);
//                    }
//                    syncInfos.add(blInfo);
//                } catch (Exception e) {
//                    log.error("pullBlInfo: " + e);
//                }
//            }
//            //回调
//            if (CollectionUtils.isNotEmpty(syncInfos)) {
//                erpSyncClient.syncBlInfoFlag(syncInfos);
//            }
//        }
//    }
//
//    @Transactional(rollbackFor = Exception.class)
//    public void pullErpSendBillInfos() throws Exception {
//        //拉取erp的sendBill信息
//        CompanyInfoDO companyInfoDO = companyInfoMapper.item(companyUtil.ynOrgId());
//        ActionResult<List<GoodsInfo>> result = erpSyncClient.pullSendInfos();
//        if (ErrorCode.Success.getCode() == result.getCode()) {
//            List<GoodsInfo> goodsInfos = result.getValue();
//            if (CollectionUtils.isNotEmpty(goodsInfos)) {
//                for (GoodsInfo goodsInfo : goodsInfos) {
//                    //处理
//                    SendBillInfoDO sendBillInfoDO = convertSendBillDO(goodsInfo, companyInfoDO);
//                    //插入
//                    sendBillMapper.mergeInto(sendBillInfoDO.getSendBillDO());
//
//                    List<SendBillDetailDO> sendBillDetailDOs = sendBillInfoDO.getSendBillDetailDOs();
//                    for (SendBillDetailDO sendBillDetailDO : sendBillDetailDOs) {
//                        sendBillDetailMapper.mergeInto(sendBillDetailDO);
//                        purchaseRequestDetailMapper.updateInformQty(sendBillDetailDO.getSourceId(), sendBillDetailDO.getMaterialsNo(), sendBillDetailDO.getSourceRowNo(), sendBillDetailDO.getRealQty());
//                        Integer state = 2;
//                        purchaseRequestMapper.updateSendStatus(sendBillDetailDO.getSourceId(), state);
//                    }
//
//                    SendBillAddVO sendBillAddVO = item(sendBillInfoDO.getSendBillDO().getId(), companyUtil.ynOrgId());
//
//                    if (sendBillAddVO != null) {
//                        SendBillDO sendBillDO = sendBillInfoDO.getSendBillDO();
//                        WarehouseInboundDO warehouseInboundDO = warehouseInboundService.getByOrder(sendBillDO.getSendOrder(), companyUtil.ynOrgId());
//                        if (warehouseInboundDO != null) {
//                            warehouseInboundService.deleteByOrder(warehouseInboundDO.getBusinessOrder(), sendBillDO.getDeliveryOrgId());
//                        }
//                        warehouseInboundService.saveBySendBill(sendBillAddVO, sendBillDO.getCreateId(),
//                                sendBillDO.getDeliveryOrgId(), sendBillDO.getApplyOrgId(), 1);
//                    }
//                }
//                //回调
//                erpSyncClient.updateSendBillSyncFlag(goodsInfos);
//                pullErpSendBillInfos();
//            }
//        } else {
//            LogHelper.error(result.getMessage(), result.getCode());
//            throw new Exception(result.getMessage());
//        }
//        pullErpSendBillDetailInfos();
//    }
//
//    private void pullErpSendBillDetailInfos() throws Exception {
//        ActionResult<List<GoodsItemVO>> result = erpSyncClient.pullSendDetailInfos();
//        if (ErrorCode.Success.getCode() == result.getCode()) {
//            List<GoodsItemVO> goodsItemVOs = result.getValue();
//            if (CollectionUtils.isNotEmpty(goodsItemVOs)) {
//                List<SendBillDetailDO> sendBillDetailDOs = convertDetailDOs(goodsItemVOs);
//                for (SendBillDetailDO sendBillDetailDO : sendBillDetailDOs) {
//                    sendBillDetailMapper.mergeInto(sendBillDetailDO);
//                }
//                erpSyncClient.updateSendBillDetailSyncFlag(goodsItemVOs);
//                pullErpSendBillDetailInfos();
//            }
//        } else {
//            LogHelper.error(result.getMessage(), result.getCode());
//            throw new Exception(result.getMessage());
//        }
//    }
//
//    private void processBlItems(List<BlItemVO> blItemVOs) {
//        if (CollectionUtils.isNotEmpty(blItemVOs)) {
//            List<SendBillDetailDO> sendBillDetailDOs = convertBlDetailDOs(blItemVOs);
//            for (SendBillDetailDO sendBillDetailDO : sendBillDetailDOs) {
//                sendBillDetailMapper.mergeInto(sendBillDetailDO);
//            }
//            erpSyncClient.syncBlItemFlag(blItemVOs);
//        }
//    }
//
//    private void pullErpBlDetailInfos() throws Exception {
//        ActionResult<Object> result = erpSyncClient.pullBlDetailCount();
//        if (ErrorCode.Success.getCode() == result.getCode()) {
//            Integer count = (Integer) result.getValue();
//            if (count != null && count > 0) {
//                int sum = count / 50;
//                int lastSum = count % 50;
//                for (int i = 0; i < sum; i++) {
//                    ActionResult<List<BlItemVO>> itemResult = erpSyncClient.pullBlItemInfos(i * 50, (i + 1) * 50);
//                    if (ErrorCode.Success.getCode() != itemResult.getCode()) {
//                        throw new Exception("查询失败");
//                    }
//                    List<BlItemVO> blItemVOs = itemResult.getValue();
//                    processBlItems(blItemVOs);
//                }
//                if (lastSum > 0) {
//                    ActionResult<List<BlItemVO>> itemResult = erpSyncClient.pullBlItemInfos(sum * 50, count);
//                    if (ErrorCode.Success.getCode() != itemResult.getCode()) {
//                        throw new Exception("查询失败");
//                    }
//                    List<BlItemVO> blItemVOs = itemResult.getValue();
//                    processBlItems(blItemVOs);
//                }
//            }
//        }
//    }
//
//    /**
//     * 转换SendBillInfoDO
//     * @return
//     */
//    private SendBillInfoDO convertSendBillDO(GoodsInfo goodsInfo, CompanyInfoDO companyInfoDO) {
//        GoodsHeaderVO header = goodsInfo.getHeaderVO();
//        SendBillDO sendBillDO = new SendBillDO();
//        sendBillDO.setId(header.getGoodsmovementid());
//        sendBillDO.setSendOrder(header.getGoodsmovementcode());
//        sendBillDO.setIsSign(0);
//        sendBillDO.setStatus(0);
//        sendBillDO.setIsDelivery(1);
//        sendBillDO.setSendType(0);
//        sendBillDO.setSoldOrgId(companyUtil.ynOrgId());
//        if (companyInfoDO == null) {
//            sendBillDO.setSoldOrgName(goodsInfo.getHeaderVO().getIsscompanyname());
//        } else {
//            sendBillDO.setSoldOrgName(companyInfoDO.getCompanyName());
//        }
//
//        List<GoodsItemVO> goodsItemVOs = goodsInfo.getItemVOs();
//
//        List<SendBillDetailDO> details = convertDetailDOs(goodsItemVOs);
//        PurchaseRequestDO requestInfo = null;
//        if (CollectionUtils.isNotEmpty(details)) {
//            requestInfo = purchaseRequestMapper.itemByBillNo(goodsItemVOs.get(0).getDlsddcode());
//        }
//
//        if (requestInfo == null) {
//            sendBillDO.setIsDel(1);
//            sendBillDO.setApplyOrgId("无");
//            sendBillDO.setApplyOrgName("无");
//            sendBillDO.setDeliveryOrgId("无");
//            sendBillDO.setDeliveryOrgName("无");
//            sendBillDO.setCreateDate(new Date());
//            sendBillDO.setCreateName("自动");
//        } else {
//            sendBillDO.setIsDel(0);
//            sendBillDO.setApplyOrgId(requestInfo.getPurchaseOrgId());
//            sendBillDO.setApplyOrgName(requestInfo.getPurchaseOrgName());
//            sendBillDO.setDeliveryOrgId(requestInfo.getDeliveryOrgId());
//            sendBillDO.setDeliveryOrgName(requestInfo.getDeliveryOrgName());
//            sendBillDO.setContactUser(requestInfo.getReceiverName());
//            sendBillDO.setContactTel(requestInfo.getReceiverTel());
//            sendBillDO.setAddress(requestInfo.getReceiverAddress());
//            sendBillDO.setDeliveryDate(requestInfo.getDeliveryDate());
//            sendBillDO.setCreateDate(new Date());
//            sendBillDO.setCreateName("自动");
//        }
//        sendBillDO.setSalesCode("1006");
//        sendBillDO.setSalesCodeDes("合肥云内");
//
//        SendBillInfoDO sendBillInfoDO = new SendBillInfoDO();
//        sendBillInfoDO.setSendBillDO(sendBillDO);
//        sendBillInfoDO.setSendBillDetailDOs(details);
//
//
//        return sendBillInfoDO;
//    }
//
//    private SendBillInfoDO convertBlToSendBillInfo(BlInfo blInfo, CompanyInfoDO companyInfoDO) {
//        BlHeadVO blHeadVO = blInfo.getBlHeadVO();
//        SendBillDO sendBillDO = new SendBillDO();
//        sendBillDO.setId(blHeadVO.getBolid());
//        sendBillDO.setSendOrder(blHeadVO.getBolcode());
//        sendBillDO.setIsSign(0);
//        sendBillDO.setStatus(0);
//        sendBillDO.setIsDelivery(1);
//        sendBillDO.setSendType(0);
//        sendBillDO.setSoldOrgId(companyUtil.ynOrgId());
//        if (companyInfoDO == null) {
//            sendBillDO.setSoldOrgName(blHeadVO.getIsscompanyname());
//        } else {
//            sendBillDO.setSoldOrgName(companyInfoDO.getCompanyName());
//        }
//
//        List<BlItemVO> blItemVOs = blInfo.getBlItemVOs();
//
//        List<SendBillDetailDO> details = convertBlDetailDOs(blItemVOs);
//        PurchaseRequestDO requestInfo = null;
//        if (CollectionUtils.isNotEmpty(details)) {
//            requestInfo = purchaseRequestMapper.itemByBillNo(blItemVOs.get(0).getDlsddcode());
//        }
//
//        if (requestInfo == null) {
//            sendBillDO.setIsDel(1);
//            sendBillDO.setApplyOrgId("无");
//            sendBillDO.setApplyOrgName("无");
//            sendBillDO.setDeliveryOrgId("无");
//            sendBillDO.setDeliveryOrgName("无");
//            sendBillDO.setCreateDate(new Date());
//            sendBillDO.setCreateName("自动");
//        } else {
//            sendBillDO.setIsDel(0);
//            sendBillDO.setApplyOrgId(requestInfo.getPurchaseOrgId());
//            sendBillDO.setApplyOrgName(requestInfo.getPurchaseOrgName());
//            sendBillDO.setDeliveryOrgId(requestInfo.getDeliveryOrgId());
//            sendBillDO.setDeliveryOrgName(requestInfo.getDeliveryOrgName());
//            sendBillDO.setContactUser(requestInfo.getReceiverName());
//            sendBillDO.setContactTel(requestInfo.getReceiverTel());
//            sendBillDO.setAddress(requestInfo.getReceiverAddress());
//            sendBillDO.setDeliveryDate(requestInfo.getDeliveryDate());
//            sendBillDO.setCreateDate(new Date());
//            sendBillDO.setCreateName("自动");
//        }
//
//        SendBillInfoDO sendBillInfoDO = new SendBillInfoDO();
//        sendBillInfoDO.setSendBillDO(sendBillDO);
//        sendBillInfoDO.setSendBillDetailDOs(details);
//
//        return sendBillInfoDO;
//    }
//
//    private List<SendBillDetailDO> convertDetailDOs(List<GoodsItemVO> goodsItemVOs) {
//        List<SendBillDetailDO> details = new ArrayList<SendBillDetailDO>();
//        if (CollectionUtils.isNotEmpty(goodsItemVOs)) {
//            int rowNo = 1;
//            for (GoodsItemVO goodsItemVO : goodsItemVOs) {
//                SendBillDetailDO detailDO = new SendBillDetailDO();
//                detailDO.setId(goodsItemVO.getGoodsmovementid() + "-" + goodsItemVO.getGoodsmovementitemid());
//                detailDO.setMainId(goodsItemVO.getGoodsmovementid());
//                detailDO.setRowNo(rowNo);
//                String sourceOrder = goodsItemVO.getDlsddcode();
//                PurchaseRequestDO requestDO = purchaseRequestMapper.itemByBillNo(sourceOrder);
//                if (requestDO != null) {
//                    detailDO.setSourceId(requestDO.getBillId());
//                    detailDO.setSourceOrder(requestDO.getBillNo());
//                    detailDO.setInitialOrder(requestDO.getDirectSourceOrder());
//                } else {
//                    detailDO.setSourceId("无");
//                    detailDO.setSourceOrder("无");
//                }
//                detailDO.setMaterialsNo(goodsItemVO.getMaterialcode());
//                detailDO.setMaterialsDes(goodsItemVO.getMaterialname());
//                detailDO.setUnit(goodsItemVO.getUnitname());
//                detailDO.setStatus(0);
//                detailDO.setQty(goodsItemVO.getTargoutquantity());
//                detailDO.setRealQty(goodsItemVO.getActoutquantity());
//                detailDO.setPostingState(0);
//                detailDO.setPostingNum(BigDecimal.ZERO);
//                rowNo++;
//                details.add(detailDO);
//            }
//        }
//        return details;
//    }
//
//    private List<SendBillDetailDO> convertBlDetailDOs(List<BlItemVO> blItemVOs) {
//        List<SendBillDetailDO> details = new ArrayList<SendBillDetailDO>();
//        if (CollectionUtils.isNotEmpty(blItemVOs)) {
//            int rowNo = 1;
//            for (BlItemVO blItemVO : blItemVOs) {
//                SendBillDetailDO detailDO = new SendBillDetailDO();
//                detailDO.setId(blItemVO.getBolid() + "-" + blItemVO.getBolitemid());
//                detailDO.setMainId(blItemVO.getBolid());
//                detailDO.setRowNo(rowNo);
//                String sourceOrder = blItemVO.getDlsddcode();
//                PurchaseRequestDO requestDO = purchaseRequestMapper.itemByBillNo(sourceOrder);
//                if (requestDO != null) {
//                    detailDO.setSourceId(requestDO.getBillId());
//                    detailDO.setSourceOrder(requestDO.getBillNo());
//                    detailDO.setInitialOrder(requestDO.getDirectSourceOrder());
//                } else {
//                    detailDO.setSourceId("无");
//                    detailDO.setSourceOrder("无");
//                }
//                detailDO.setMaterialsNo(blItemVO.getMaterialcode());
//                detailDO.setMaterialsDes(blItemVO.getMaterialname());
//                detailDO.setUnit(blItemVO.getUnitname());
//                detailDO.setStatus(0);
//                detailDO.setQty(blItemVO.getTargoutquantity());
//                detailDO.setRealQty(BigDecimal.ZERO);
//                detailDO.setPostingState(0);
//                detailDO.setPostingNum(BigDecimal.ZERO);
//                rowNo++;
//                details.add(detailDO);
//            }
//        }
//        return details;
//    }

    /**
     * 根据出库单更新送货单
     * @param sendOrder
     * @param materialsNo
     * @param realAmount
     * @param singleState
     * @param totalState
     * @return
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean updateByOutbound(String sendOrder, String materialsNo, BigDecimal realAmount,
                                    Integer singleState, Integer totalState) throws Exception {
        SendBillDO sendBillDO = sendBillMapper.getBySendOrder(sendOrder);
        if (null == sendBillDO) {
            return false;
        }

        //如果是单条零件按照一个处理，如果是多条零件按照顺序处理
        List<SendBillDetailDO> detailDOs = sendBillDetailMapper.findByMainIdAndMaterialNo(sendBillDO.getId(), materialsNo, null);
        if (CollectionUtils.isEmpty(detailDOs)) {
            return false;
        }

        if(Integer.valueOf(1).equals(sendBillDO.getSendType()) || detailDOs.size() == 1) {
            SendBillDetailDO detailDO = detailDOs.get(0);
            BigDecimal outboundQty = detailDO.getOutboundQty() == null ? BigDecimal.ZERO : detailDO.getOutboundQty();
            detailDO.setOutboundQty(outboundQty.add(realAmount));
            detailDO.setOutboundStatus(singleState);
            boolean success = sendBillDetailMapper.update(detailDO) > 0;
            if (success) {
                sendBillDO.setOutboundStatus(totalState);//出库状态
                success = sendBillMapper.update(sendBillDO) > 0;
                if (!success) {
                    return false;
                }
            }
            return success;
        }else {
            //按顺序处理
            BigDecimal lastAmount = realAmount;
            for (SendBillDetailDO detailDO : detailDOs) {
                if (lastAmount.compareTo(BigDecimal.ZERO) <= 0) {
                    continue;
                }
                BigDecimal qty = detailDO.getQty() == null ? BigDecimal.ZERO : detailDO.getQty();
                BigDecimal outboundQty = detailDO.getOutboundQty() == null ? BigDecimal.ZERO : detailDO.getOutboundQty();
                if (qty.compareTo(outboundQty) <= 0) {
                    continue;
                }
                BigDecimal minQty = qty.subtract(outboundQty);
                if (minQty.compareTo(lastAmount) >= 0) {
                    detailDO.setOutboundQty(outboundQty.add(lastAmount));
                    //已出库
                    detailDO.setOutboundStatus(2);
                    lastAmount = BigDecimal.ZERO;
                } else {
                    detailDO.setOutboundQty(outboundQty.add(minQty));
                    //部分出口库
                    detailDO.setOutboundStatus(1);
                    lastAmount = lastAmount.subtract(minQty);
                }
                sendBillDetailMapper.update(detailDO);
            }

            Boolean flag = true;
            for (SendBillDetailDO detailDO : detailDOs) {
                flag = flag && (Integer.valueOf(2).equals(detailDO.getOutboundStatus()));
            }
            if (flag) {
                sendBillDO.setOutboundStatus(2);
            } else {
                sendBillDO.setOutboundStatus(1);
            }
            sendBillMapper.update(sendBillDO);
            return true;
        }
    }

    /**
     * 更新到货时间
     * @param id
     * @param arrivalDate
     */
    public ErrorCode updateArrivalDate(String id, Date arrivalDate) {
        SendBillDO sendBillDO = new SendBillDO();
        sendBillDO.setId(id);
        sendBillDO.setArrivalDate(arrivalDate);
        sendBillDO.setIsArrival(1);
        return sendBillMapper.update(sendBillDO) > 0 ? ErrorCode.Success : ErrorCode.Failure;
    }

}
